package com.ruoyi.gis.geoserver.service;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.gis.GeoserverConfig;
import com.ruoyi.gis.domain.GeoLayer;
import com.ruoyi.gis.domain.GisLayer;
import com.ruoyi.gis.geoserver.domain.*;
import com.ruoyi.gis.vo.RasterStyleConfig;
import it.geosolutions.geoserver.rest.GeoServerRESTManager;
import it.geosolutions.geoserver.rest.GeoServerRESTPublisher;
import it.geosolutions.geoserver.rest.GeoServerRESTReader;
import it.geosolutions.geoserver.rest.decoder.*;
import it.geosolutions.geoserver.rest.decoder.utils.NameLinkElem;
import it.geosolutions.geoserver.rest.encoder.GSLayerEncoder;
import it.geosolutions.geoserver.rest.encoder.GSLayerGroupEncoder;
import it.geosolutions.geoserver.rest.encoder.coverage.GSCoverageEncoder;
import it.geosolutions.geoserver.rest.encoder.coverage.GSImageMosaicEncoder;
import it.geosolutions.geoserver.rest.encoder.datastore.GSGeoTIFFDatastoreEncoder;
import it.geosolutions.geoserver.rest.encoder.datastore.GSPostGISDatastoreEncoder;
import it.geosolutions.geoserver.rest.encoder.datastore.GSShapefileDatastoreEncoder;
import it.geosolutions.geoserver.rest.encoder.feature.GSFeatureTypeEncoder;
import it.geosolutions.geoserver.rest.manager.GeoServerRESTStyleManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

//参考文档
//https://www.osgeo.cn/geoserver-user-manual/rest/api/
//postman: https://blog.csdn.net/weixin_43947145/article/details/118809246
//java : https://www.jianshu.com/p/662641fa2704
//geosolutions-it/geoserver-manager  https://blog.csdn.net/qq_41731732/article/details/109293175

@Service
public class GeoserverService {
    Logger logger = LoggerFactory.getLogger(GeoserverService.class);

    @Autowired
    private GeoserverConfig geoserverConfig;

    public List<String> listWorkspace() throws MalformedURLException {
        GeoServerRESTManager manager = new GeoServerRESTManager(new URL(geoserverConfig.getEndpoint()),
                geoserverConfig.getAccessKey(), geoserverConfig.getSecretKey());
        GeoServerRESTReader reader = manager.getReader();
        RESTWorkspaceList workspaces = reader.getWorkspaces();
        return reader.getWorkspaceNames();
    }

    public List<String> listWorkspaceStore(String workspace) throws MalformedURLException {
        GeoServerRESTManager manager = new GeoServerRESTManager(new URL(geoserverConfig.getEndpoint()),
                geoserverConfig.getAccessKey(), geoserverConfig.getSecretKey());
        GeoServerRESTReader reader = manager.getReader();
        RESTDataStoreList datastores = reader.getDatastores(workspace);
        List<String> result = new ArrayList<>();
        if(datastores!=null){
            for(NameLinkElem item:datastores){
                result.add(item.getName());
            }
        }
        return result;
    }

    public List<String> listWorkspaceStoreLayers(String workspace,String store) throws MalformedURLException {
        GeoServerGwcRESTManager manager = new GeoServerGwcRESTManager(new URL(geoserverConfig.getEndpoint()),
                geoserverConfig.getAccessKey(), geoserverConfig.getSecretKey());
        StoreFeature dataStoreFeatureTypes = manager.getDataStoreFeatureTypes(workspace, store);
        List<String> result = new ArrayList<>();
        if(dataStoreFeatureTypes!=null&&dataStoreFeatureTypes.getFeatureTypes()!=null){
            for(StoreFeatureType item:dataStoreFeatureTypes.getFeatureTypes().getFeatureType()){
                result.add(item.getName());
            }
        }
        return result;
    }
//    public List<String> listWorkspaceLayers(String workspace) throws MalformedURLException {
//        GeoServerRESTManager manager = new GeoServerRESTManager(new URL(geoserverConfig.getEndpoint()),
//                geoserverConfig.getAccessKey(), geoserverConfig.getSecretKey());
//        GeoServerRESTReader reader = manager.getReader();
//        RESTLayerList layers = reader.getLayers();
//        List<String> result = new ArrayList<>();
//        if(layers!=null){
//            for(NameLinkElem item:layers){
//                result.add(item.getName());
//            }
//        }
//        return result;
//    }

    public List<String> listLayerGroups() throws MalformedURLException {
        GeoServerRESTManager manager = new GeoServerRESTManager(new URL(geoserverConfig.getEndpoint()),
                geoserverConfig.getAccessKey(), geoserverConfig.getSecretKey());
        GeoServerRESTReader reader = manager.getReader();
        RESTLayerGroupList layerGroups = reader.getLayerGroups();
        List<String> groupResult = new ArrayList<>();
        if(layerGroups!=null){
            for(NameLinkElem item:layerGroups){
                groupResult.add(item.getName());
            }
        }
        return groupResult;
    }

    //请勿用中文
    public GeoServerLayerGroup getLayerGroupConfig(String layerGroup) {
        try {
            GeoServerGwcRESTManager gwcRESTManager = new GeoServerGwcRESTManager(new URL(geoserverConfig.getEndpoint()),
                    geoserverConfig.getAccessKey(), geoserverConfig.getSecretKey());
            GeoServerLayerGroup layerGroupConfig = gwcRESTManager.getLayerGroupConfig(layerGroup);
            return layerGroupConfig;
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        }
    }

//    private void setLayerGroupUrlAndBbox(String layerGroupName,String workspaceName,String layerName) {
//        GeoServerRESTManager manager = new GeoServerRESTManager(new URL(geoserverConfig.getEndpoint()),
//                geoserverConfig.getAccessKey(), geoserverConfig.getSecretKey());
//        RESTLayerGroup restLayerGroup = manager.getReader()
//                .getLayerGroup(workspaceName, layerGroupName);
//        String nativeCrs = restLayerGroup.getCRS();
//        layerGroup.setLayer(geoServerProperties.getWorkSpaceName() + ":" + layerGroupName);
//        layerGroup.setBboxMinX(restLayerGroup.getMinX());
//        layerGroup.setBboxMinY(restLayerGroup.getMinY());
//        layerGroup.setBboxMaxX(restLayerGroup.getMaxX());
//        layerGroup.setBboxMaxY(restLayerGroup.getMaxY());
////返回图层预览wms地址
//        /*return geoServerProperties.getEndpoint() + "/" + geoServerProperties.getWorkSpaceName() + "/wms?service=WMS&version=1.1.0&request=GetMap&layers=" + geoServerProperties.getWorkSpaceName() + ":" + layerGroupName + "&bbox="
//                + nativeMinX + "," + nativeMinY + "," + nativeMaxX + "," + nativeMaxY +
//                //todo 宽高写死了
//                "&width=768&height=330&srs=" + nativeCrs + "&styles=&format=application/openlayers";*/
//        //返回图层预览缓存gwc地址-wmts
//        layerGroup.setLayerGroupUrl(geoServerProperties.getEndpoint() + "/gwc/demo/" + geoServerProperties.getWorkSpaceName() + ":" + layerGroupName + "?gridSet="
//                + nativeCrs + "&format=image/png");
//    }


    /**
     * 创建图层组
     * @param layerGroupName 图层组名称
     * @param layersList     图层名称队列：格式为WorkSpace：图层名称 eg： ja-test:tiff-test
     * @return 是否成功
     */
    public boolean createLayerGroup(String workspaceName,String layerGroupName,
                                    ArrayList<String> layersList) throws MalformedURLException {
        GSLayerGroupEncoder gsLayerGroupEncoder = new GSLayerGroupEncoder();
        gsLayerGroupEncoder.setWorkspace(workspaceName);
        gsLayerGroupEncoder.setName(layerGroupName);
        for (String layer : layersList) {
            gsLayerGroupEncoder.addLayer(layer);
        }
        GeoServerRESTManager manager = new GeoServerRESTManager(new URL(geoserverConfig.getEndpoint()),
                geoserverConfig.getAccessKey(), geoserverConfig.getSecretKey());
        return manager.getPublisher().createLayerGroup(workspaceName, layerGroupName, gsLayerGroupEncoder);
    }
    /**
     * 调用geoserver为图层组配置图层
     */
    public boolean configureLayerGroup(String workspaceName,String layerGroupName, ArrayList<String> layersList) throws MalformedURLException {
        GSLayerGroupEncoder gsLayerGroupEncoder = new GSLayerGroupEncoder();
        gsLayerGroupEncoder.setWorkspace(workspaceName);
        gsLayerGroupEncoder.setName(layerGroupName);
        for (String layer : layersList) {
            gsLayerGroupEncoder.addLayer(layer);
        }
        GeoServerRESTManager manager = new GeoServerRESTManager(new URL(geoserverConfig.getEndpoint()),
                geoserverConfig.getAccessKey(), geoserverConfig.getSecretKey());
        return manager.getPublisher().configureLayerGroup(workspaceName, layerGroupName, gsLayerGroupEncoder);
    }



    public GeoLayer getLayer(String workspaceName, String layerName)throws IOException {
        GeoServerRESTManager manager = new GeoServerRESTManager(new URL(geoserverConfig.getEndpoint()),
                geoserverConfig.getAccessKey(), geoserverConfig.getSecretKey());
//        GeoServerRESTPublisher publisher = manager.getPublisher();
//        GeoServerRESTReader reader = manager.getReader();
//        if (!reader.existsWorkspace(workspaceName)) {
//            boolean create_workspace = publisher.createWorkspace(workspaceName);
//            System.out.println("create workspace : " + create_workspace);
//        } else {
//            System.out.println("workspace已经存在了,workspaceName :" + workspaceName);
//        }
        //判断图层是否已经存在，不存在则创建并发布
//        RESTLayer layer = reader.getLayer(workspaceName, layerName);
        GeoServerGwcRESTManager manager2 = new GeoServerGwcRESTManager(new URL(geoserverConfig.getEndpoint()),
                geoserverConfig.getAccessKey(), geoserverConfig.getSecretKey());
        RESTLayer layer = manager2.getLayer(workspaceName, layerName);
        if (layer != null) {
            GeoLayer geoLayer = new GeoLayer();
            String resourceUrl = layer.getResourceUrl();
            RESTWms wms = manager.getReader().getWms(layer);//通过getResourceUrl()
            String crs = wms.getCRS();
            String storeType = wms.getStoreType();
            String storeName = wms.getStoreName();
            GroupBounds boundary = new GroupBounds();
            boundary.setMaxx(wms.getMaxX());
            boundary.setMaxy(wms.getMaxY());
            boundary.setMinx(wms.getMinX());
            boundary.setMiny(wms.getMinY());
            geoLayer.setBoundary(boundary);
            geoLayer.setSourceUrl(geoserverConfig.getEndpoint());
            geoLayer.setType(layer.getType().name().toLowerCase());
            geoLayer.setStyle(layer.getDefaultStyle().toLowerCase());
            geoLayer.setCrs(crs);
            geoLayer.setName(wms.getName());
            geoLayer.setTitle(wms.getTitle());
            geoLayer.setStoreType(storeType);
            geoLayer.setStoreName(storeName);
            geoLayer.setSourceUrl(resourceUrl);
            //属性表
//            List<Map<FeatureTypeAttribute, String>> attributeList = wms.getAttributeList();
            return geoLayer;
        }
        return null;
    }
    public boolean removeLayer(String storeType,String workspaceName,
                               String store,String layerName)throws IOException {
        GeoServerRESTManager manager = new GeoServerRESTManager(new URL(geoserverConfig.getEndpoint()),
                geoserverConfig.getAccessKey(), geoserverConfig.getSecretKey());
//        GeoServerRESTPublisher publisher = manager.getPublisher();
        GeoServerRESTPublisher publisher = manager.getPublisher();
        boolean result = publisher.removeLayer(workspaceName, layerName);
        if(result){
            if(GisLayer.store_coverageStore.equals(storeType)){
                publisher.removeCoverageStore(workspaceName,store);
                logger.info("removeCoverageStore................... ");
            }else if(GisLayer.store_dataStore.equals(storeType)){
                publisher.removeDatastore(workspaceName,store);
                logger.info("removeDatastore..................... ");
            }
        }
        return result;
    }
    public GeoServerLayer getLayerConfig(String workspaceAndlayerName) throws MalformedURLException, UnsupportedEncodingException {
        GeoServerGwcRESTManager gwcRESTManager = new GeoServerGwcRESTManager(new URL(geoserverConfig.getEndpoint()),
                geoserverConfig.getAccessKey(), geoserverConfig.getSecretKey());
        GeoServerLayer layerConfig = gwcRESTManager.getLayerConfig(workspaceAndlayerName);
        return layerConfig;
    }


    public void updateLayerTitleCache(String workspace, String layerName, String sourceFormat) throws MalformedURLException, UnsupportedEncodingException {
        GeoServerGwcRESTManager manager = new GeoServerGwcRESTManager(new URL(geoserverConfig.getEndpoint()),
                geoserverConfig.getAccessKey(), geoserverConfig.getSecretKey());
        GeoServerLayer layerConfig = manager.getLayerConfig(workspace, layerName);
        if(layerConfig!=null){
            String[] mimeFormats = null;//layerConfig.getMimeFormats();
            if(layerConfig.getMimeFormats()==null){
                mimeFormats= new String[1];
                mimeFormats[0]=sourceFormat;
            }else {
                mimeFormats= new String[layerConfig.getMimeFormats().length+1];
                mimeFormats[0]=sourceFormat;
                for(int i=0;i<layerConfig.getMimeFormats().length;i++){
                    mimeFormats[i+1]=layerConfig.getMimeFormats()[i];
                }
            }
//            if(!mimeFormats.contains(sourceFormat)){
//                mimeFormats.add(sourceFormat);
//            }
            layerConfig.setMimeFormats(mimeFormats);
            manager.setLayerConfig(workspace,layerName,layerConfig);
        }
    }


    /**
     * 发布tif格式数据
     *  不建议
     * @throws IOException
     */
    public boolean publishGeoTIFF(File tifFile,
                                  String workspace,String store, String layerName,String srs
    )throws IOException {
        GeoServerRESTManager manager = new GeoServerRESTManager(new URL(geoserverConfig.getEndpoint()),
                geoserverConfig.getAccessKey(), geoserverConfig.getSecretKey());
        GeoServerRESTPublisher publisher = manager.getPublisher();
        GeoServerRESTReader reader = manager.getReader();
        /**
         * 获取reader 和 publisher的另一种方式
         * GeoServerRESTPublisher geoServerRESTPublisher = new GeoServerRESTPublisher(url, username, passwd);
         * GeoServerRESTReader geoServerRESTReader = new GeoServerRESTReader(url, username, passwd);
         *
         */
        // 检查workspace 若不存在，创建workspace
        List<String> workspaceNames = reader.getWorkspaceNames();
        if (!workspaceNames.contains(workspace)) {
            boolean publisherWorkspace = publisher.createWorkspace(workspace);
            System.out.println("create workspace : " + publisherWorkspace);
        } else {
            System.out.println("workspace已经存在了,workspace name :" + workspace);
        }
        RESTDataStore restStore = reader.getDatastore(workspace, store);
        if (restStore == null) {
            //tif只能在不同的存储中，否则发布失败
            GSGeoTIFFDatastoreEncoder gsGeoTIFFDatastoreEncoder = new GSGeoTIFFDatastoreEncoder(store);
            gsGeoTIFFDatastoreEncoder.setWorkspaceName(workspace);
//            new URL("file:" + layerName)
            URL tifFileUrl = tifFile.toURL();// new URL();//URL("file:data/"+workspace+"/"+store);
            gsGeoTIFFDatastoreEncoder.setUrl(tifFileUrl);
//            gsGeoTIFFDatastoreEncoder.setUrl(new URL(storeUrl));
            boolean createStore = manager.getStoreManager().create(workspace, gsGeoTIFFDatastoreEncoder);
            System.out.println("create store (TIFF文件创建状态) : " + createStore);
            if(createStore){
                boolean publish = manager.getPublisher().publishGeoTIFF(workspace, store,layerName, tifFile);


                System.out.println("publish (TIFF文件发布状态) : " + publish);
                return publish;
            }
        } else {
            System.out.println("数据存储已经存在了,store:" + store);
        }
        return false;
    }


    /**
     * 发布tif格式图层
     * @param tifFile  tif文件全路径
     * @param workspace
     * @param layerName
     * @param layerTitle
     * @param srs
     * @throws Exception
     */
    public boolean publishExternalGeoTIFF(File tifFile,String workspace,String storeName,
                                          String layerName,String layerTitle, String srs) throws Exception {
        logger.info("publishExternalGeoTIFF................");
        GeoServerRESTManager manager = new GeoServerRESTManager(new URL(geoserverConfig.getEndpoint()),
                geoserverConfig.getAccessKey(), geoserverConfig.getSecretKey());
        GeoServerRESTReader reader = manager.getReader();
        GeoServerRESTPublisher publisher = manager.getPublisher();
        // 检查workspace 若不存在，创建workspace
        List<String> workspaceNames = reader.getWorkspaceNames();
        if (!workspaceNames.contains(workspace)) {
            logger.info("create workspace not exist and will create");
            boolean publisherWorkspace = publisher.createWorkspace(workspace);
            logger.info("create workspace : " + publisherWorkspace);
        } else {
            logger.info("workspace已经存在了,workspace name :" + workspace);
        }
        //GSCoverageEncoder
        GSImageMosaicEncoder gsCoverageEncoder = new GSImageMosaicEncoder();
        //设置坐标系
        gsCoverageEncoder.setSRS(srs);//("EPSG:4326");
        gsCoverageEncoder.setName(layerName);
        gsCoverageEncoder.setTitle(layerTitle);


//        RESTCoverageStore restStore = reader.getCoverageStore(workspace, storeName);
//        if (restStore == null) {
//            System.out.println("store not exit : " + storeName);
//        } else {
//            System.out.println("数据存储已经存在了,store:" + storeName);
//            manager.getStoreManager().remove(workspaceNames,gsCoverageEncoder,false);
//        }
        //todo 去斜拍照片的黑边，但是会导致图层发白，清晰度丢失，暂无解决办法（样式？）
        GSLayerEncoder layerEncoder = new GSLayerEncoder();
        if(layerTitle.contains("ndvi")){
            layerEncoder.setDefaultStyle("default-raster");
        }
        else {
            gsCoverageEncoder.setInputTransparentColor("#000000");
        }
//
        logger.info("publishTiffData publishExternalGeoTIFF start ..........");
        RESTCoverageStore publish = publisher.publishExternalGeoTIFF(
                workspace, storeName, tifFile, gsCoverageEncoder, layerEncoder);
        logger.info("publishTiffData layerName:{} layerTitle:{} publish (TIFF文件发布状态) : {}", layerName, layerTitle, publish);
        return publish!=null?true:false;
    }




    /**
     * 发布shapefile数据  geoserver 会把shp压缩文件解压缩到的/data/workspace/storeName下
     * @param shpZip  //shp文件压缩包，必须是zip压缩包，且shp文件(.shp、.dbf、.shx等)外层不能有文件夹，且压缩包名称需要与shp图层名称一致
     * @param workspace
     * @param store
     * @param layerName  必须和shpZip文件名称一样
     * @param srs
     * @return
     * @throws IOException
     */
    public boolean publishShpData(File shpZip,
                                  String workspace, String store,
                                  String layerName, String srs) throws IOException {
        //压缩文件的完整路径
        GeoServerRESTManager manager = new GeoServerRESTManager(new URL(geoserverConfig.getEndpoint()),
                geoserverConfig.getAccessKey(), geoserverConfig.getSecretKey());
        GeoServerRESTPublisher publisher = manager.getPublisher();
        GeoServerRESTReader reader = manager.getReader();
        if (!reader.existsWorkspace(workspace)) {
            boolean create_workspace = publisher.createWorkspace(workspace);
            System.out.println("create workspace : " + create_workspace);
        } else {
            System.out.println("workspace已经存在了,workspace :" + workspace);
        }
        //https://blog.csdn.net/qq_36871430/article/details/128664671
        //shp文件所在的位置
        //判断数据存储（datastore）是否已经存在，不存在则创建
//        String urlDatastore = "file://"+"D:\\dev\\Data\\矢量\\191206-开发区建筑矢量图\\build.shp";
//        //判断数据存储（datastore）是否已经存在，不存在则创建
//        URL shpFileUrl = new URL(urlDatastore);
        URL shpFileUrl = new URL("file:data/"+workspace+"/"+store);
//        URL shpFileUrl = new URL("file:"+geoserverConfig.getDataDirRoot()+"/"+workspace+"/"+store);
        RESTDataStore restStore = reader.getDatastore(workspace, store);
        if (restStore == null) {
            //创建shape文件存储
            GSShapefileDatastoreEncoder datastoreEncoder = new GSShapefileDatastoreEncoder(store, shpFileUrl);
            boolean createStore = manager.getStoreManager().create(workspace, datastoreEncoder);
            System.out.println("create store : " + createStore);
        } else {
            System.out.println("数据存储已经存在了,store:" + store);
        }
        //判断图层是否已经存在，不存在则创建并发布
        RESTLayer layer = reader.getLayer(workspace, layerName);
        if (layer == null) {
            //发布图层
            boolean publish = manager.getPublisher().publishShp(workspace,
                    store, layerName, shpZip, srs);//GeoServerRESTPublisher.DEFAULT_CRS);
            //https://stackoverflow.com/questions/55299517/connection-reset-by-peer-socket-write-error-httpclient-and-geoserver
            //Connection reset by peer: socket write error httpclient and geoserver
            System.out.println("publish : " + publish);
//            RESTWms wms = manager.getReader().getWms(layer);
//            RESTBoundingBox nativeBoundingBox = wms.getNativeBoundingBox();
            return publish;
        } else {
            System.out.println("表已经发布过了,table:" + store);
        }
        return false;
    }



    //https://blog.csdn.net/October_zhang/article/details/124490256
    //发布postgis中的数据
    public void publishPostGISData(
            String workspaceName,String storeName,
            String storeUrl,String layerName) throws IOException {
        String table_name = layerName; // 数据库要发布的表名称,后面图层名称和表名保持一致
        //判断工作区（workspace）是否存在，不存在则创建
        GeoServerRESTManager manager = new GeoServerRESTManager(new URL(geoserverConfig.getEndpoint()),
                geoserverConfig.getAccessKey(), geoserverConfig.getSecretKey());
        GeoServerRESTPublisher publisher = manager.getPublisher();
        List<String> workspaces = manager.getReader().getWorkspaceNames();
        if (!workspaces.contains(workspaceName)) {
            boolean createws = publisher.createWorkspace(workspaceName);
            System.out.println("create ws : " + createws);
        } else {
            System.out.println("workspace已经存在了,ws :" + workspaceName);
        }
        //判断数据存储（datastore）是否已经存在，不存在则创建
        RESTDataStore restStore = manager.getReader().getDatastore(workspaceName, storeName);
        if (restStore == null) {
            GSPostGISDatastoreEncoder store = new GSPostGISDatastoreEncoder(storeName);
            //postgis连接配置
            store.setHost(geoserverConfig.getHost());//设置url
            store.setPort(geoserverConfig.getPort());//设置端口
            store.setUser(geoserverConfig.getUsername());// 数据库的用户名
            store.setPassword(geoserverConfig.getPassword());// 数据库的密码
            store.setDatabase(geoserverConfig.getDatabase());// 那个数据库;
            store.setSchema("public"); //当前先默认使用public这个schema
            store.setConnectionTimeout(20);// 超时设置
            //store.setName(schema);
            store.setMaxConnections(20); // 最大连接数
            store.setMinConnections(1);     // 最小连接数
            store.setExposePrimaryKeys(true);
            boolean createStore = manager.getStoreManager().create(workspaceName, store);
            System.out.println("create store : " + createStore);
        } else {
            System.out.println("数据存储已经存在了,store:" + storeName);
        }
        //判断图层是否已经存在，不存在则创建并发布
        RESTLayer layer = manager.getReader().getLayer(workspaceName, table_name);
        if (layer == null) {
            GSFeatureTypeEncoder pds = new GSFeatureTypeEncoder();
            pds.setTitle(table_name);
            pds.setName(table_name);
            pds.setSRS("EPSG:4326");
            GSLayerEncoder layerEncoder = new GSLayerEncoder();
            boolean publish = manager.getPublisher().publishDBLayer(workspaceName,
                    storeName, pds, layerEncoder);
            System.out.println("publish : " + publish);
        } else {
            System.out.println("表已经发布过了,table:" + table_name);
        }
    }

    public boolean publishStyle(String workspace,String sldBody, String styleName) throws MalformedURLException {
        GeoServerRESTManager manager = new GeoServerRESTManager(new URL(geoserverConfig.getEndpoint()),
                geoserverConfig.getAccessKey(), geoserverConfig.getSecretKey());
        GeoServerRESTStyleManager styleManager = manager.getStyleManager();
        RESTStyle style = styleManager.getStyle(workspace, styleName);
        if (style != null) {
            return styleManager.updateStyleInWorkspace(workspace,sldBody,styleName);
        }
        return styleManager.publishStyleInWorkspace(workspace,sldBody,styleName);
    }

    public boolean deleteStyle(String sldBody, String name) throws MalformedURLException {
        GeoServerRESTManager manager = new GeoServerRESTManager(new URL(geoserverConfig.getEndpoint()),
                geoserverConfig.getAccessKey(), geoserverConfig.getSecretKey());
        GeoServerRESTStyleManager styleManager = manager.getStyleManager();
        return styleManager.publishStyle(sldBody,name);
    }

    public void updateLayerStyle(String workspace, String layerName, String styleName) throws MalformedURLException {
        GeoServerRESTManager manager = new GeoServerRESTManager(new URL(geoserverConfig.getEndpoint()),
                geoserverConfig.getAccessKey(), geoserverConfig.getSecretKey());
        GeoServerRESTPublisher publisher = manager.getPublisher();
        GSLayerEncoder layerEncoder = new GSLayerEncoder();
        layerEncoder.setDefaultStyle(workspace,styleName);
        publisher.configureLayer(workspace,layerName,layerEncoder);
    }


    public void updateCoverageConfig(String workspace,
                                  String layerName,
                                  String layerTitle,
                                  String srs, String transparentColor) throws MalformedURLException {
        GeoServerRESTManager manager = new GeoServerRESTManager(new URL(geoserverConfig.getEndpoint()),
                geoserverConfig.getAccessKey(), geoserverConfig.getSecretKey());
        GeoServerRESTPublisher publisher = manager.getPublisher();
        GSImageMosaicEncoder gsCoverageEncoder = new GSImageMosaicEncoder();
        //设置坐标系
        gsCoverageEncoder.setSRS(srs);//("EPSG:4326");
        gsCoverageEncoder.setName(layerName);
        gsCoverageEncoder.setTitle(layerTitle);
//        RESTCoverageStore restStore = reader.getCoverageStore(workspace, storeName);
//        if (restStore == null) {
//            System.out.println("store not exit : " + storeName);
//        } else {
//            System.out.println("数据存储已经存在了,store:" + storeName);
//            manager.getStoreManager().remove(workspaceNames,gsCoverageEncoder,false);
//        }
        //todo 去斜拍照片的黑边，但是会导致图层发白，清晰度丢失，暂无解决办法（样式？）
        if(!StringUtils.isEmpty(transparentColor)){
            gsCoverageEncoder.setInputTransparentColor(transparentColor);
        }
        publisher.configureCoverage(gsCoverageEncoder,workspace,layerName);
    }



//    public static void main(String[] args) throws IOException {
//        //GeoServer的连接配置
//        String url = "http://192.168.10.101:8080/geoserver";
//        String username = "admin";
//        String password = "public@2qax";
//        String workspace = "testWs";
//        String store = "testStore";
//        String storeTif = "testTifStore2";
//        String crs = GeoServerRESTPublisher.DEFAULT_CRS;
//        String layerName = "youcai2";
////        GeoserverPublishTiffData(url, username, password);
////        GeoserverPublishShapefileData(url, username, password);  //发布shp数据
//        // GeoserverPublishPostGISData(url, username, passwd);
//        GeoServerRESTManager manager = new GeoServerRESTManager(new URL(url),
//                username, password);
//        File file = new File("D:\\ruoyi\\uploadPath\\gisCatch\\youcai2.zip");
//        GeoServerRESTPublisher publisher = manager.getPublisher();
//        GeoServerRESTReader reader = manager.getReader();
//        //该请求是put请求，资划所的网络禁用了put请求
////        boolean publish = manager.getPublisher().publishShp(workspace,
////                store, layerName, file, crs);
//
//
//        File tifFile = new File("D:\\work\\油菜\\油菜\\youcai_rgb\\youcai_rgb.tif");
//        // 检查workspace 若不存在，创建workspace
//        List<String> workspaceNames = reader.getWorkspaceNames();
//        if (!workspaceNames.contains(workspace)) {
//            boolean publisherWorkspace = publisher.createWorkspace(workspace);
//            System.out.println("create workspace : " + publisherWorkspace);
//        } else {
//            System.out.println("workspace已经存在了,workspace name :" + workspace);
//        }
//        RESTDataStore restStore = reader.getDatastore(workspace, storeTif);
//        if (restStore == null) {
//            //tif只能在不同的存储中，否则发布失败
//            GSGeoTIFFDatastoreEncoder gsGeoTIFFDatastoreEncoder = new GSGeoTIFFDatastoreEncoder(storeTif);
//            gsGeoTIFFDatastoreEncoder.setWorkspaceName(workspace);
////            new URL("file:" + layerName)
//            URL tifFileUrl = new URL("file:data/"+workspace+"/"+storeTif);
//            gsGeoTIFFDatastoreEncoder.setUrl(tifFileUrl);
////            gsGeoTIFFDatastoreEncoder.setUrl(new URL(storeUrl));
//            boolean createStore = manager.getStoreManager().create(workspace, gsGeoTIFFDatastoreEncoder);
//            System.out.println("create store (TIFF文件创建状态) : " + createStore);
//            if(createStore){
//                boolean publish = manager.getPublisher().
//                        publishGeoTIFF(workspace, store,layerName, tifFile);
//                System.out.println("publish (TIFF文件发布状态) : " + publish);
//            }
//        } else {
//            System.out.println("数据存储已经存在了,store:" + store);
//        }
//    }
}
